<!--
 * @Description: 销售分析页面 - 提供销售数据的深度分析和可视化展示
 * @Author: lujq
 * @Date: 2025-08-13
 * @LastEditors: lujq
 * @LastEditTime: 2025-08-13 14:00:00
-->
<template>
  <div class="sales-analytics">
    <!-- 销售概览 -->
    <div class="overview-section">
      <el-row :gutter="20">
        <el-col :xs="24" :sm="12" :md="6" v-for="item in overviewData" :key="item.title">
          <el-card class="overview-card" shadow="hover">
            <div class="card-content">
              <div class="card-icon" :style="{ backgroundColor: item.color }">
                <el-icon :size="20">
                  <component :is="item.icon" />
                </el-icon>
              </div>
              <div class="card-info">
                <div class="card-title">{{ item.title }}</div>
                <div class="card-value">{{ item.value }}</div>
                <div class="card-trend" :class="item.trend > 0 ? 'positive' : 'negative'">
                  <el-icon size="12">
                    <ArrowUp v-if="item.trend > 0" />
                    <ArrowDown v-else />
                  </el-icon>
                  {{ Math.abs(item.trend) }}%
                </div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 筛选条件 -->
    <div class="filter-section">
      <el-card>
        <el-form :model="filterForm" :inline="true" class="filter-form">
          <el-form-item label="时间范围">
            <el-date-picker
              v-model="filterForm.dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              @change="handleFilter"
            />
          </el-form-item>
          <el-form-item label="产品类别">
            <el-select
              style="width: 100px"
              v-model="filterForm.category"
              placeholder="请选择产品类别"
              clearable
              @change="handleFilter"
              @clear="handleFilter"
            >
              <el-option label="真丝面料" value="silk" />
              <el-option label="棉质面料" value="cotton" />
              <el-option label="羊毛面料" value="wool" />
              <el-option label="化纤面料" value="synthetic" />
            </el-select>
          </el-form-item>
          <el-form-item label="销售渠道">
            <el-select
              style="width: 100px"
              v-model="filterForm.channel"
              placeholder="请选择销售渠道"
              clearable
              @change="handleFilter"
              @clear="handleFilter"
            >
              <el-option label="线上销售" value="online" />
              <el-option label="线下门店" value="offline" />
              <el-option label="批发渠道" value="wholesale" />
              <el-option label="代理商" value="agent" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleFilter">
              <el-icon><Search /></el-icon>
              查询
            </el-button>
            <el-button @click="handleReset">
              <el-icon><Refresh /></el-icon>
              重置
            </el-button>
            <el-button type="success" @click="handleExport">
              <el-icon><Download /></el-icon>
              导出报告
            </el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>

    <!-- 图表分析区域 -->
    <div class="charts-section">
      <el-row :gutter="20">
        <!-- 销售趋势图 -->
        <el-col :xs="24" :lg="12">
          <el-card class="chart-card">
            <template #header>
              <div class="card-header">
                <span class="card-title">销售趋势</span>
                <el-select v-model="salesPeriod" size="small" style="width: 120px">
                  <el-option label="最近7天" value="7d" />
                  <el-option label="最近30天" value="30d" />
                  <el-option label="最近90天" value="90d" />
                  <el-option label="最近一年" value="1y" />
                </el-select>
              </div>
            </template>
            <div ref="salesTrendChart" class="chart-container"></div>
          </el-card>
        </el-col>

        <!-- 销售渠道分布 -->
        <el-col :xs="24" :lg="12">
          <el-card class="chart-card">
            <template #header>
              <span class="card-title">销售渠道分布</span>
            </template>
            <div ref="channelChart" class="chart-container"></div>
          </el-card>
        </el-col>
      </el-row>

      <el-row :gutter="20" style="margin-top: 20px">
        <!-- 产品类别销售 -->
        <el-col :xs="24" :lg="12">
          <el-card class="chart-card">
            <template #header>
              <span class="card-title">产品类别销售</span>
            </template>
            <div ref="categoryChart" class="chart-container"></div>
          </el-card>
        </el-col>

        <!-- 销售员业绩 -->
        <el-col :xs="24" :lg="12">
          <el-card class="chart-card">
            <template #header>
              <span class="card-title">销售员业绩排行</span>
            </template>
            <div ref="salesmanChart" class="chart-container"></div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 地区销售分析 -->
      <el-row style="margin-top: 20px">
        <el-col :span="24">
          <el-card class="chart-card">
            <template #header>
              <span class="card-title">地区销售分析</span>
            </template>
            <div ref="regionChart" class="chart-container" style="height: 400px"></div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 销售预测 -->
      <el-row style="margin-top: 20px">
        <el-col :span="24">
          <el-card class="chart-card">
            <template #header>
              <div class="card-header">
                <span class="card-title">销售预测</span>
                <el-select v-model="forecastModel" size="small" style="width: 150px">
                  <el-option label="线性回归" value="linear" />
                  <el-option label="指数平滑" value="exponential" />
                  <el-option label="ARIMA模型" value="arima" />
                </el-select>
              </div>
            </template>
            <div ref="forecastChart" class="chart-container" style="height: 400px"></div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 数据表格 -->
    <div class="data-section">
      <el-row :gutter="20">
        <!-- 热销产品 -->
        <el-col :xs="24" :lg="8">
          <el-card class="table-card">
            <template #header>
              <div class="card-header">
                <span class="card-title">热销产品TOP10</span>
                <el-button type="text" size="small" @click="viewAllProducts"> 查看全部 </el-button>
              </div>
            </template>
            <el-table :data="hotProducts" stripe max-height="300">
              <el-table-column prop="rank" label="排名" width="60" align="center" />
              <el-table-column prop="name" label="产品名称" show-overflow-tooltip />
              <el-table-column prop="sales" label="销量" width="80" align="right" />
            </el-table>
          </el-card>
        </el-col>

        <!-- 优秀销售员 -->
        <el-col :xs="24" :lg="8">
          <el-card class="table-card">
            <template #header>
              <div class="card-header">
                <span class="card-title">优秀销售员</span>
                <el-button type="text" size="small" @click="viewAllSalesmen"> 查看全部 </el-button>
              </div>
            </template>
            <el-table :data="topSalesmen" stripe max-height="300">
              <el-table-column prop="rank" label="排名" width="60" align="center" />
              <el-table-column prop="name" label="姓名" />
              <el-table-column prop="performance" label="业绩" width="100" align="right">
                <template #default="{ row }"> ¥{{ formatNumber(row.performance) }} </template>
              </el-table-column>
            </el-table>
          </el-card>
        </el-col>

        <!-- 重点客户 -->
        <el-col :xs="24" :lg="8">
          <el-card class="table-card">
            <template #header>
              <div class="card-header">
                <span class="card-title">重点客户</span>
                <el-button type="text" size="small" @click="viewAllCustomers"> 查看全部 </el-button>
              </div>
            </template>
            <el-table :data="keyCustomers" stripe max-height="300">
              <el-table-column prop="name" label="客户名称" show-overflow-tooltip />
              <el-table-column prop="contribution" label="贡献度" width="80" align="right">
                <template #default="{ row }"> {{ row.contribution }}% </template>
              </el-table-column>
            </el-table>
          </el-card>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, nextTick, watch } from 'vue'
import * as echarts from 'echarts'
import {
  Money,
  TrendCharts,
  ShoppingCart,
  User,
  ArrowUp,
  ArrowDown,
  Search,
  Refresh,
  Download,
} from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { formatNumber } from '@/utils'
import { useRouter } from 'vue-router'

// 路由实例
const router = useRouter()

// 图表实例
const salesTrendChart = ref<HTMLElement>()
const channelChart = ref<HTMLElement>()
const categoryChart = ref<HTMLElement>()
const salesmanChart = ref<HTMLElement>()
const regionChart = ref<HTMLElement>()
const forecastChart = ref<HTMLElement>()

let salesTrendChartInstance: echarts.ECharts
let channelChartInstance: echarts.ECharts
let categoryChartInstance: echarts.ECharts
let salesmanChartInstance: echarts.ECharts
let regionChartInstance: echarts.ECharts
let forecastChartInstance: echarts.ECharts

// 筛选表单
const filterForm = reactive({
  dateRange: [] as string[],
  category: '',
  channel: '',
})

// 数据
const salesPeriod = ref('30d')
const forecastModel = ref('linear')

// 概览数据
const overviewData = ref([
  {
    title: '总销售额',
    value: '¥2.34M',
    trend: 18.5,
    icon: 'Money',
    color: '#409EFF',
  },
  {
    title: '销售增长率',
    value: '15.2%',
    trend: 12.3,
    icon: 'TrendCharts',
    color: '#67C23A',
  },
  {
    title: '订单转化率',
    value: '68.9%',
    trend: -2.1,
    icon: 'ShoppingCart',
    color: '#E6A23C',
  },
  {
    title: '客户满意度',
    value: '94.5%',
    trend: 5.7,
    icon: 'User',
    color: '#F56C6C',
  },
])

// 热销产品数据
const hotProducts = ref([
  { rank: 1, name: '高档真丝面料', sales: 1256 },
  { rank: 2, name: '纯棉印花布', sales: 1134 },
  { rank: 3, name: '羊毛呢料', sales: 1028 },
  { rank: 4, name: '亚麻混纺布', sales: 956 },
  { rank: 5, name: '涤纶面料', sales: 887 },
  { rank: 6, name: '丝绸缎面', sales: 823 },
  { rank: 7, name: '棉麻混纺', sales: 756 },
  { rank: 8, name: '雪纺面料', sales: 689 },
  { rank: 9, name: '牛仔布料', sales: 634 },
  { rank: 10, name: '针织面料', sales: 578 },
])

// 优秀销售员数据
const topSalesmen = ref([
  { rank: 1, name: '张三', performance: 567000 },
  { rank: 2, name: '李四', performance: 489000 },
  { rank: 3, name: '王五', performance: 423000 },
  { rank: 4, name: '赵六', performance: 356000 },
  { rank: 5, name: '钱七', performance: 298000 },
])

// 重点客户数据
const keyCustomers = ref([
  { name: '上海时装有限公司', contribution: 15.6 },
  { name: '北京服饰集团', contribution: 12.3 },
  { name: '广州纺织厂', contribution: 10.8 },
  { name: '深圳制衣公司', contribution: 9.2 },
  { name: '杭州丝绸企业', contribution: 8.7 },
])

/**
 * 处理筛选查询
 */
const handleFilter = () => {
  ElMessage.success('筛选条件已应用')
  console.log('筛选条件:', filterForm)
  updateDataByFilter()
  updateCharts()
}

/**
 * 重置筛选条件
 */
const handleReset = () => {
  filterForm.dateRange = []
  filterForm.category = ''
  filterForm.channel = ''
  ElMessage.info('筛选条件已重置')
  resetToInitialData()
  updateCharts()
}

/**
 * 导出报告
 */
const handleExport = () => {
  ElMessage.success('销售报告导出中...')
}

/**
 * 查看全部产品
 */
const viewAllProducts = () => {
  router.push({
    name: 'ProductList',
    query: {
      title: '全部产品列表'
    }
  })
}

/**
 * 查看全部销售员
 */
const viewAllSalesmen = () => {
  router.push({
    name: 'OrderList',
    query: {
      title: '销售员相关订单列表'
    }
  })
}

/**
 * 查看全部客户
 */
const viewAllCustomers = () => {
  router.push({
    name: 'CustomerList',
    query: {
      title: '重点客户列表',
    }
  })
}

/**
 * 初始化销售趋势图表
 */
const initSalesTrendChart = () => {
  if (!salesTrendChart.value) return

  salesTrendChartInstance = echarts.init(salesTrendChart.value)

  // 根据筛选条件和时间周期生成数据
  const trendData = generateSalesTrendData()

  const option = {
    tooltip: {
      trigger: 'axis',
    },
    legend: {
      data: ['销售额', '利润', '订单数'],
    },
    xAxis: {
      type: 'category',
      data: trendData.xAxisData,
    },
    yAxis: [
      {
        type: 'value',
        name: '金额(万元)',
        position: 'left',
      },
      {
        type: 'value',
        name: '订单数',
        position: 'right',
      },
    ],
    series: [
      {
        name: '销售额',
        type: 'line',
        yAxisIndex: 0,
        data: trendData.salesData,
        smooth: true,
        itemStyle: {
          color: '#409EFF',
        },
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: 'rgba(64, 158, 255, 0.3)' },
            { offset: 1, color: 'rgba(64, 158, 255, 0.1)' },
          ]),
        },
      },
      {
        name: '利润',
        type: 'line',
        yAxisIndex: 0,
        data: trendData.profitData,
        smooth: true,
        itemStyle: {
          color: '#67C23A',
        },
      },
      {
        name: '订单数',
        type: 'bar',
        yAxisIndex: 1,
        data: trendData.orderData,
        itemStyle: {
          color: '#E6A23C',
        },
      },
    ],
  }

  salesTrendChartInstance.setOption(option)
}

/**
 * 初始化销售渠道图表
 */
const initChannelChart = () => {
  if (!channelChart.value) return

  channelChartInstance = echarts.init(channelChart.value)

  const option = {
    tooltip: {
      trigger: 'item',
    },
    legend: {
      orient: 'vertical',
      left: 'left',
    },
    series: [
      {
        name: '销售渠道',
        type: 'pie',
        radius: ['40%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2,
        },
        label: {
          show: false,
          position: 'center',
        },
        emphasis: {
          label: {
            show: true,
            fontSize: 20,
            fontWeight: 'bold',
          },
        },
        labelLine: {
          show: false,
        },
        data: [
          { value: 456, name: '线上销售' },
          { value: 234, name: '线下门店' },
          { value: 156, name: '批发渠道' },
          { value: 89, name: '代理商' },
        ],
      },
    ],
  }

  channelChartInstance.setOption(option)
}

/**
 * 初始化产品类别图表
 */
const initCategoryChart = () => {
  if (!categoryChart.value) return

  categoryChartInstance = echarts.init(categoryChart.value)

  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow',
      },
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true,
    },
    xAxis: {
      type: 'category',
      data: ['真丝面料', '棉质面料', '羊毛面料', '化纤面料', '混纺面料'],
    },
    yAxis: {
      type: 'value',
      name: '销售额(万元)',
    },
    series: [
      {
        name: '销售额',
        type: 'bar',
        data: [234, 189, 156, 134, 98],
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: '#83bff6' },
            { offset: 0.5, color: '#188df0' },
            { offset: 1, color: '#188df0' },
          ]),
        },
      },
    ],
  }

  categoryChartInstance.setOption(option)
}

/**
 * 初始化销售员业绩图表
 */
const initSalesmanChart = () => {
  if (!salesmanChart.value) return

  salesmanChartInstance = echarts.init(salesmanChart.value)

  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow',
      },
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true,
    },
    xAxis: {
      type: 'value',
    },
    yAxis: {
      type: 'category',
      data: ['钱七', '赵六', '王五', '李四', '张三'],
    },
    series: [
      {
        name: '业绩',
        type: 'bar',
        data: [29.8, 35.6, 42.3, 48.9, 56.7],
        itemStyle: {
          color: '#67C23A',
        },
      },
    ],
  }

  salesmanChartInstance.setOption(option)
}

/**
 * 初始化地区销售图表
 */
const initRegionChart = () => {
  if (!regionChart.value) return

  regionChartInstance = echarts.init(regionChart.value)

  const option = {
    tooltip: {
      trigger: 'axis',
    },
    legend: {
      data: ['华东地区', '华南地区', '华北地区', '西南地区', '其他地区'],
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true,
    },
    xAxis: {
      type: 'category',
      data: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'],
    },
    yAxis: {
      type: 'value',
      name: '销售额(万元)',
    },
    series: [
      {
        name: '华东地区',
        type: 'line',
        data: [78, 89, 95, 87, 98, 105, 112, 125, 134, 142, 156, 168],
        smooth: true,
      },
      {
        name: '华南地区',
        type: 'line',
        data: [45, 52, 58, 62, 68, 75, 82, 89, 95, 102, 108, 115],
        smooth: true,
      },
      {
        name: '华北地区',
        type: 'line',
        data: [33, 38, 42, 45, 48, 52, 56, 61, 65, 69, 73, 78],
        smooth: true,
      },
      {
        name: '西南地区',
        type: 'line',
        data: [22, 25, 28, 31, 34, 37, 40, 43, 46, 49, 52, 55],
        smooth: true,
      },
      {
        name: '其他地区',
        type: 'line',
        data: [12, 15, 18, 21, 24, 27, 30, 33, 36, 39, 42, 45],
        smooth: true,
      },
    ],
  }

  regionChartInstance.setOption(option)
}

/**
 * 初始化销售预测图表
 */
const initForecastChart = () => {
  if (!forecastChart.value) return

  forecastChartInstance = echarts.init(forecastChart.value)

  const option = {
    tooltip: {
      trigger: 'axis',
    },
    legend: {
      data: ['历史数据', '预测数据', '置信区间'],
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true,
    },
    xAxis: {
      type: 'category',
      data: [
        '1月',
        '2月',
        '3月',
        '4月',
        '5月',
        '6月',
        '7月',
        '8月',
        '9月',
        '10月',
        '11月',
        '12月',
        '1月+',
        '2月+',
        '3月+',
      ],
    },
    yAxis: {
      type: 'value',
      name: '销售额(万元)',
    },
    series: [
      {
        name: '历史数据',
        type: 'line',
        data: [156, 189, 234, 198, 267, 298, 345, 389, 423, 456, 489, 523, null, null, null],
        smooth: true,
        itemStyle: {
          color: '#409EFF',
        },
      },
      {
        name: '预测数据',
        type: 'line',
        data: [
          null,
          null,
          null,
          null,
          null,
          null,
          null,
          null,
          null,
          null,
          null,
          523,
          556,
          589,
          623,
        ],
        smooth: true,
        itemStyle: {
          color: '#67C23A',
        },
        lineStyle: {
          type: 'dashed',
        },
      },
      {
        name: '置信区间',
        type: 'line',
        data: [
          null,
          null,
          null,
          null,
          null,
          null,
          null,
          null,
          null,
          null,
          null,
          null,
          520,
          550,
          580,
        ],
        smooth: true,
        itemStyle: {
          color: '#E6A23C',
        },
        lineStyle: {
          type: 'dotted',
        },
        areaStyle: {
          color: 'rgba(230, 162, 60, 0.1)',
        },
      },
    ],
  }

  forecastChartInstance.setOption(option)
}

/**
 * 根据筛选条件生成销售趋势数据
 */
const generateSalesTrendData = () => {
  let xAxisData: string[]
  let baseSalesData: number[]
  let baseProfitData: number[]
  let baseOrderData: number[]

  // 根据时间周期生成不同的数据
  switch (salesPeriod.value) {
    case '7d':
      xAxisData = ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
      baseSalesData = [156, 189, 234, 198, 267, 298, 245]
      baseProfitData = [78, 95, 117, 99, 134, 149, 123]
      baseOrderData = [45, 52, 68, 58, 76, 89, 67]
      break
    case '30d':
      xAxisData = Array.from({ length: 30 }, (_, i) => `${i + 1}日`)
      baseSalesData = Array.from({ length: 30 }, () => Math.floor(Math.random() * 200) + 150)
      baseProfitData = Array.from({ length: 30 }, () => Math.floor(Math.random() * 100) + 70)
      baseOrderData = Array.from({ length: 30 }, () => Math.floor(Math.random() * 50) + 40)
      break
    case '90d':
      xAxisData = Array.from({ length: 90 }, (_, i) => `第${Math.floor(i / 7) + 1}周`).filter(
        (_, i) => i % 7 === 0,
      )
      baseSalesData = Array.from({ length: 13 }, () => Math.floor(Math.random() * 300) + 200)
      baseProfitData = Array.from({ length: 13 }, () => Math.floor(Math.random() * 150) + 100)
      baseOrderData = Array.from({ length: 13 }, () => Math.floor(Math.random() * 80) + 60)
      break
    case '1y':
    default:
      xAxisData = [
        '1月',
        '2月',
        '3月',
        '4月',
        '5月',
        '6月',
        '7月',
        '8月',
        '9月',
        '10月',
        '11月',
        '12月',
      ]
      baseSalesData = [156, 189, 234, 198, 267, 298, 345, 389, 423, 456, 489, 523]
      baseProfitData = [78, 95, 117, 99, 134, 149, 173, 195, 212, 228, 245, 262]
      baseOrderData = [45, 52, 68, 58, 76, 89, 95, 108, 125, 134, 142, 156]
      break
  }

  // 根据筛选条件调整数据
  const hasFilter = filterForm.dateRange.length > 0 || filterForm.category || filterForm.channel
  if (hasFilter) {
    const filterMultiplier = Math.random() * 0.4 + 0.8 // 0.8-1.2之间的随机数
    baseSalesData = baseSalesData.map((val) => Math.floor(val * filterMultiplier))
    baseProfitData = baseProfitData.map((val) => Math.floor(val * filterMultiplier))
    baseOrderData = baseOrderData.map((val) => Math.floor(val * filterMultiplier))
  }

  return {
    xAxisData,
    salesData: baseSalesData,
    profitData: baseProfitData,
    orderData: baseOrderData,
  }
}

/**
 * 根据筛选条件生成销售渠道数据
 */
const generateChannelData = () => {
  const baseData = [
    { value: 456, name: '线上销售' },
    { value: 234, name: '线下门店' },
    { value: 156, name: '批发渠道' },
    { value: 89, name: '代理商' },
  ]

  // 根据筛选条件调整数据
  const hasFilter = filterForm.dateRange.length > 0 || filterForm.category || filterForm.channel
  if (hasFilter) {
    const filterMultiplier = Math.random() * 0.4 + 0.8 // 0.8-1.2之间的随机数
    return baseData.map((item) => ({
      ...item,
      value: Math.floor(item.value * filterMultiplier),
    }))
  }

  return baseData
}

/**
 * 根据筛选条件生成产品类别数据
 */
const generateCategoryData = () => {
  const baseData = [234, 189, 156, 134, 98]

  // 根据筛选条件调整数据
  const hasFilter = filterForm.dateRange.length > 0 || filterForm.category || filterForm.channel
  if (hasFilter) {
    const filterMultiplier = Math.random() * 0.4 + 0.8 // 0.8-1.2之间的随机数
    return baseData.map((val) => Math.floor(val * filterMultiplier))
  }

  return baseData
}

/**
 * 根据筛选条件生成销售员业绩数据
 */
const generateSalesmanData = () => {
  const baseData = [234, 189, 156, 134, 98, 87, 76, 65, 54, 43]

  // 根据筛选条件调整数据
  const hasFilter = filterForm.dateRange.length > 0 || filterForm.category || filterForm.channel
  if (hasFilter) {
    const filterMultiplier = Math.random() * 0.4 + 0.8 // 0.8-1.2之间的随机数
    return baseData.map((val) => Math.floor(val * filterMultiplier))
  }

  return baseData
}

/**
 * 根据筛选条件生成地区销售数据
 */
const generateRegionData = () => {
  const baseData = [
    { name: '北京', value: 234 },
    { name: '天津', value: 123 },
    { name: '上海', value: 345 },
    { name: '重庆', value: 156 },
    { name: '河北', value: 189 },
    { name: '河南', value: 267 },
    { name: '云南', value: 98 },
    { name: '辽宁', value: 145 },
    { name: '黑龙江', value: 87 },
    { name: '湖南', value: 198 },
    { name: '安徽', value: 134 },
    { name: '山东', value: 298 },
    { name: '新疆', value: 76 },
    { name: '江苏', value: 356 },
    { name: '浙江', value: 289 },
    { name: '江西', value: 167 },
    { name: '湖北', value: 189 },
    { name: '广西', value: 123 },
    { name: '甘肃', value: 65 },
    { name: '山西', value: 145 },
    { name: '内蒙古', value: 98 },
    { name: '陕西', value: 156 },
    { name: '吉林', value: 87 },
    { name: '福建', value: 234 },
    { name: '贵州', value: 76 },
    { name: '广东', value: 456 },
    { name: '青海', value: 34 },
    { name: '西藏', value: 23 },
    { name: '四川', value: 267 },
    { name: '宁夏', value: 45 },
    { name: '海南', value: 67 },
    { name: '台湾', value: 123 },
    { name: '香港', value: 89 },
    { name: '澳门', value: 34 },
  ]

  // 根据筛选条件调整数据
  const hasFilter = filterForm.dateRange.length > 0 || filterForm.category || filterForm.channel
  if (hasFilter) {
    const filterMultiplier = Math.random() * 0.4 + 0.8 // 0.8-1.2之间的随机数
    return baseData.map((item) => ({
      ...item,
      value: Math.floor(item.value * filterMultiplier),
    }))
  }

  return baseData
}

/**
 * 根据筛选条件生成销售预测数据
 */
const generateForecastData = () => {
  const baseHistoryData = [156, 189, 234, 198, 267, 298, 345, 389, 423, 456, 489, 523]
  const baseForecastData = [567, 612, 658, 689, 734, 778]

  // 根据筛选条件和预测模型调整数据
  const hasFilter = filterForm.dateRange.length > 0 || filterForm.category || filterForm.channel
  let historyData = [...baseHistoryData]
  let forecastData = [...baseForecastData]

  if (hasFilter) {
    const filterMultiplier = Math.random() * 0.4 + 0.8 // 0.8-1.2之间的随机数
    historyData = historyData.map((val) => Math.floor(val * filterMultiplier))
    forecastData = forecastData.map((val) => Math.floor(val * filterMultiplier))
  }

  // 根据预测模型调整预测数据
  if (forecastModel.value === 'exponential') {
    forecastData = forecastData.map((val, index) => Math.floor(val * (1 + index * 0.1)))
  } else if (forecastModel.value === 'polynomial') {
    forecastData = forecastData.map((val, index) =>
      Math.floor(val * (1 + Math.pow(index, 1.2) * 0.05)),
    )
  }

  return { historyData, forecastData }
}

/**
 * 根据筛选条件更新数据
 */
const updateDataByFilter = () => {
  // 根据筛选条件更新概览数据
  const hasFilter = filterForm.dateRange.length > 0 || filterForm.category || filterForm.channel
  if (hasFilter) {
    const filterMultiplier = Math.random() * 0.4 + 0.8 // 0.8-1.2之间的随机数
    overviewData.value = overviewData.value.map((item) => {
      const baseValue = parseFloat(item.value.replace(/[^\d.]/g, ''))
      const newValue = Math.floor(baseValue * filterMultiplier)
      return {
        ...item,
        value: item.value.includes('¥')
          ? `¥${(newValue / 100).toFixed(1)}M`
          : item.value.includes('%')
            ? `${newValue.toFixed(1)}%`
            : newValue.toString(),
      }
    })
  }
}

/**
 * 重新初始化所有图表
 */
const updateCharts = () => {
  nextTick(() => {
    initSalesTrendChart()
    initChannelChart()
    initCategoryChart()
    initSalesmanChart()
    initRegionChart()
    initForecastChart()
  })
}

/**
 * 重置为初始数据
 */
const resetToInitialData = () => {
  // 重置概览数据
  overviewData.value = [
    {
      title: '总销售额',
      value: '¥2.34M',
      trend: 18.5,
      icon: 'Money',
      color: '#409EFF',
    },
    {
      title: '销售增长率',
      value: '15.2%',
      trend: 12.3,
      icon: 'TrendCharts',
      color: '#67C23A',
    },
    {
      title: '订单转化率',
      value: '68.9%',
      trend: -2.1,
      icon: 'ShoppingCart',
      color: '#E6A23C',
    },
    {
      title: '客户满意度',
      value: '94.5%',
      trend: 5.7,
      icon: 'User',
      color: '#F56C6C',
    },
  ]
}

// 监听销售周期变化
watch(salesPeriod, () => {
  console.log('更新销售趋势:', salesPeriod.value)
  nextTick(() => {
    initSalesTrendChart()
  })
})

// 监听预测模型变化
watch(forecastModel, () => {
  console.log('更新预测模型:', forecastModel.value)
})

/**
 * 窗口大小变化时重新调整图表
 */
const handleResize = () => {
  salesTrendChartInstance?.resize()
  channelChartInstance?.resize()
  categoryChartInstance?.resize()
  salesmanChartInstance?.resize()
  regionChartInstance?.resize()
  forecastChartInstance?.resize()
}

onMounted(async () => {
  await nextTick()

  // 初始化所有图表
  initSalesTrendChart()
  initChannelChart()
  initCategoryChart()
  initSalesmanChart()
  initRegionChart()
  initForecastChart()

  // 监听窗口大小变化
  window.addEventListener('resize', handleResize)
})
</script>

<style scoped>
.sales-analytics {
  padding: 0;
}

.overview-section {
  margin-bottom: 20px;
}

.overview-card {
  height: 100px;
  cursor: pointer;
  transition: all 0.3s;
}

.overview-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.card-content {
  display: flex;
  align-items: center;
  height: 100%;
}

.card-icon {
  width: 50px;
  height: 50px;
  border-radius: 10px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 12px;
  color: white;
}

.card-info {
  flex: 1;
}

.card-title {
  font-size: 12px;
  color: #909399;
  margin-bottom: 4px;
}

.card-value {
  font-size: 20px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 2px;
}

.card-trend {
  font-size: 11px;
  display: flex;
  align-items: center;
  gap: 2px;
}

.card-trend.positive {
  color: #67c23a;
}

.card-trend.negative {
  color: #f56c6c;
}

.filter-section {
  margin-bottom: 20px;
}

.filter-form {
  margin: 0;
}

.charts-section {
  margin-bottom: 20px;
}

.chart-card,
.table-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.chart-container {
  height: 300px;
  width: 100%;
}

.data-section {
  margin-top: 20px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .overview-card {
    margin-bottom: 16px;
  }

  .card-content {
    flex-direction: column;
    text-align: center;
  }

  .card-icon {
    margin-right: 0;
    margin-bottom: 8px;
  }

  .chart-container {
    height: 250px;
  }

  .card-header {
    flex-direction: column;
    gap: 10px;
    align-items: flex-start;
  }

  .filter-form {
    display: block;
  }

  .filter-form .el-form-item {
    display: block;
    margin-bottom: 16px;
  }
}
</style>
